package ta.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DruidConnection {
    private static DataSource ds;
    private static String dbname;
    static {
		// 方法1
		InputStream res=Thread.currentThread().getContextClassLoader().getResourceAsStream("druid.properties");
		//InputStream res=DruidConnection.class.getClassLoader().getResourceAsStream("druid.properties");
    	Properties pro=new Properties();
    	try {
			pro.load(res);
			dbname=pro.getProperty("dbname");
			ds= DruidDataSourceFactory.createDataSource(pro);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    public  static DataSource getDataSource() {
		return ds;
	}
   
    public static Connection getConnection() {
		try {
			Connection  connection= ds.getConnection();
			System.out.println("数据库连接成功！");
			return connection;
		} catch (SQLException e) {
			System.out.println("数据库连接失败！");
			e.printStackTrace();
		}
		return null;
	}
    
    public static void main(String[] args) {
		ta.utils.DruidConnection.getConnection();
	}

	public static String getDbname() {
		return dbname;
	}

	public static void setDbname(String dbname) {
		ta.utils.DruidConnection.dbname = dbname;
	}
    
}
